package com.kizitonwose.calendarview.ui;

import com.kizitonwose.calendarview.CalendarView;
import com.kizitonwose.calendarview.model.CalendarDay;
import com.kizitonwose.calendarview.utils.LogUtil;

import java.time.YearMonth;

public class CalendarLayoutManager {
    private static final String TAG = "CalendarLayoutManager";
    private CalendarView calView;

    public CalendarLayoutManager(CalendarView calView) {
        this.calView = calView;
    }

    public void scrollToMonth(YearMonth month) {
        scrollToPosition(getItemProvider().getAdapterPosition(month), false);
    }

    public void smoothScrollToMonth(YearMonth month) {
        scrollToPosition(getItemProvider().getAdapterPosition(month), true);
    }

    public void scrollToDay(CalendarDay day) {
        scrollToPosition(getItemProvider().getAdapterPosition(day), false);
    }

    public void smoothScrollToDay(CalendarDay day) {
        scrollToPosition(getItemProvider().getAdapterPosition(day), true);
    }

    /**
     * 滑动到指定位置
     *
     * @param position
     */
    public synchronized void scrollToPosition(int position, boolean isSmoothScroll) {
        System.out.println(TAG+"position == "+position);
        if (position < 0) {
            return;
        }
        calView.getContext().getUITaskDispatcher().asyncDispatchBarrier(() -> {
            calView.scrollTo(position);
            LogUtil.info(TAG , "我滑动到了月份："+position);
        });
        calView.getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                getItemProvider().notifyMonthScrollListenerIfNeeded();
            }
        });
        /*calView.getContext().getUITaskDispatcher().delayDispatch(() -> {
            if (!isSmoothScroll) {
                getItemProvider().notifyMonthScrollListenerIfNeeded();
            }
        }, 120);*/
    }

    public CalendarAdapter getItemProvider() {
        return (CalendarAdapter) calView.getItemProvider();
    }
}
